<template>
  <VPage class="app-container">
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-input
          v-model.trim="form.channelName"
          placeholder="渠道名称"
          clearable
          class="w-50"
        />
        <VSelectOpt v-model="form.state" params="state" placeholder="状态" />
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions" />
      </template>
      <template #fundMoveDetail="{ row }">
        <el-button type="primary" link>查看</el-button>
      </template>
    </VTable>
    <Add
      v-model="addVisible"
      :title="addTitle"
      :data="addData"
      :options="optionsData"
      @refresh="refresh"
      @close="addData = ''"
    />
    <VLog
      v-model="logVisible"
      :autoLoad="false"
      :module="2"
      :id="logId"
      @close="logId = ''"
    />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { getChannelList, stateChannel } from "./api.js";
import { useEnumSelect } from "@/hooks/index.js";
import Add from "./add/index.vue";
import { baseAuthList } from "@/Auth/base.js";
const { proxy } = getCurrentInstance();
const { options: optionsData } = useEnumSelect({
  params: [
    "account_channel_type",
    "account_api_channel_type",
    "state",
    "channel_type",
  ],
});
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {},
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    {
      type: "checkbox",
      width: 50,
      fixed: "left",
    },
    {
      title: "ID",
      field: "id",
      width: 180,
      slots: {
        default: ({ row }) => {
          return <span>{row?.id?.toString()}</span>;
        },
      },
    },
    {
      title: "类型",
      field: "channelType",
      width: 100,
      slots: {
        default: ({ row }) => {
          return <div>{row?.channelType?.label || "-"}</div>;
        },
      },
    },
    {
      title: "渠道名称",
      field: "channelName",
      minWidth: 100,
    },
    {
      title: "渠道类型",
      field: "accountChannelType",
      width: 100,
      slots: {
        default: ({ row }) => {
          return <div>{row?.accountChannelType?.label || "-"}</div>;
        },
      },
    },
    {
      title: "渠道API",
      field: "todo",
      minWidth: 100,
    },
    {
      title: "主账号数量",
      field: "mainAccountsNumber",
      width: 100,
    },
    {
      title: "子账号数量",
      field: "subAccountsNumber",
      width: 100,
    },
    {
      title: "备注信息",
      field: "remark",
      minWidth: 100,
    },
    {
      title: "状态",
      field: "state",
      slots: {
        default: ({ row }) => {
          return <statusRender code={row.state} />;
        },
      },
      width: 100,
    },
    {
      title: "添加人",
      field: "createUser",
      width: 170,
    },
    {
      title: "添加时间",
      field: "todo",
      width: 170,
    },
    {
      title: "操作",
      width: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {[baseAuthList.channel.edit] ? (
                <el-button type="primary" link onClick={() => handleAdd(row)}>
                  编辑
                </el-button>
              ) : (
                ""
              )}
              {[baseAuthList.channel.log] ? (
                <el-button
                  type="primary"
                  link
                  onClick={() => handleLog(row.id)}
                >
                  日志
                </el-button>
              ) : (
                ""
              )}
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        return getChannelList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});

const addVisible = ref(false);
const addData = ref(null);
const addTitle = ref("新增");
const handleAdd = (row) => {
  addVisible.value = true;
  let data = null;
  if (row?.id) {
    data = {
      ...row,
      state: row?.state?.value || null,
      channelType: row?.channelType?.value || null,
      apiChannelType: row?.apiChannelType?.value || null,
      accountChannelType: row?.accountChannelType?.value || null,
    };
  }
  addData.value = data || null;
  addTitle.value = data?.id ? "编辑" : "新增";
};
const handelStatus = (name, en) => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  const handle = {
    enable: async () => {
      const { code, message } = await stateChannel({ ids, state: 1 });
      if (code !== 200) return;
      ElMessage.success("启用成功!");
      refresh();
    },
    disabled: async () => {
      try {
        const { code, message } = await stateChannel({ ids, state: 0 });
        if (code !== 200) return;
        ElMessage.success("禁用成功!");
        refresh();
      } catch (error) {}
    },
  };
  // handle[name]();
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认{en}
        <span class="text-[#3366F1] px-[4px]">{ids.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await handle[name]();
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
        }
      } else {
        done();
      }
    },
  });
};

const logVisible = ref(false);
const logId = ref("");
const handleLog = (item) => {
  logId.value = item;
  logVisible.value = true;
};

const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const actions = [
  {
    label: "新增",
    type: "primary",
    icon: "add1",
    fn: () => handleAdd(null),
    permission: [baseAuthList.channel.add],
  },
  {
    label: "启用",
    icon: "state_enable",
    iconStyle: {
      color: "var(--main-color)",
    },
    fn: () => handelStatus("enable", "启用"),
    permission: [baseAuthList.channel.enable],
  },
  {
    label: "禁用",
    icon: "state_disabled",
    iconStyle: {
      color: "var(--info-color)",
    },
    fn: () => handelStatus("disabled", "禁用"),
    permission: [baseAuthList.channel.disabled],
  },
];
</script>
<style lang="scss" scoped></style>
